/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Basketball;

import VISIE.characters.BasketballAgent;
import VISIE.characters.BasketballCharacter;
import VISIE.characters.KinectPlayer;
import VISIE.characters.NonUserPlayer;
import VISIE.characters.Player;
import VISIE.characters.Team;
import VISIE.mathfunctions.Conversions;
import VISIE.scenemanager.Court;
import VISIE.scenemanager.SceneCharacterManager;
import VISIE.scenemanager.SceneCreator;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.font.Rectangle;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import java.awt.Font;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author DiveshLala
 */
public class GameStateManagement {
    
    Ball ball;
    ArrayList<Team> teams;
    static int[] score;
    Player player;
    BitmapFont guiFont;
    BitmapFont JFont;
    int[] resolution;
    private int mainScreen = 0; //change if immersive
    private boolean twoTouch = false;

    
    public GameStateManagement(Ball b, ArrayList<Team> t, Player p, BitmapFont f, BitmapFont jf, int[] r){
        ball = b;
        teams = t;
        score = new int[2];
        player = p;
        guiFont = f;
        JFont = jf;
        resolution = r;
    }
    
    public void setMainScreen(int i){
        mainScreen = i;
    }
    
    public void doGameStateManagement(Node guiNode){
        
          int state = GameManager.getGameState();
          int attackingTeam = GameManager.getAttackingTeam();
          BasketballCharacter possessionCharacter = SceneCharacterManager.getCharacterInPossession();
          

          if(state != 0){    
              //forbids player from grabbing ball between turns
              if(possessionCharacter != null && possessionCharacter.getTeamID() == attackingTeam){
                    possessionCharacter.removePossession();
                    if(possessionCharacter instanceof VISIE.characters.BasketballAgent){
                        BasketballAgent ba = (BasketballAgent)possessionCharacter;
                        ba.setActionState(1);
                    }
              }
              else if(this.isBallOut()){
                  this.doOutOfBoundsActivity();
              }
              else if(possessionCharacter instanceof Player  || possessionCharacter instanceof NonUserPlayer){
                  
                  if(state == 3){
                        GameManager.setPossessionSwapState();
                  }

                    if(state == 2 && 
                       possessionCharacter.getPosition().setY(0).distance(Court.getRestartLocation()) < 5 &&
                       !this.isBallOut()){
                        GameManager.setInState();
                        GameManager.setAttackingTeam(possessionCharacter.getTeamID());
                        System.out.println("play restarted");
                    }
              }
          }
                    
          if(state == 0){//ball is out
              if(this.isBallOut()){
                   this.doOutOfBoundsActivity();
              }         
              else if(possessionCharacter != null &&
                   possessionCharacter.getTeamID() != attackingTeam){//ball is stolen
                   GameManager.setPossessionSwapState();
              }
              else if(this.getBallPos().distance(Court.getHoopLocation()) < 0.75f && 
                    Math.abs(this.getBallPos().y - Court.getHoopLocation().y) < 0.2f &&
                    ball.getBallTravellingDirection().y < 0){//ball in goal
                    GameManager.setScoreState();
                    ball.stopBall();     
                    if(twoTouch){
                        score[attackingTeam] = score[attackingTeam]+ 2;
                    }
                    else{
                        score[attackingTeam]++;
                    }
                    this.setScoreText(guiNode);
              }  
          }

          //process game when in
          if(state == 1 && 
             possessionCharacter != null &&
             possessionCharacter.getTeamID() != attackingTeam &&
             !this.isBallOut()){
              this.doResetActivity();
              System.out.println("Play restarted");
          }
          
          if(state != 0){
              for(int i = 0; i< teams.size(); i++){
                  if(teams.get(i).getTeamID() != attackingTeam){
                        Team t = teams.get(i); 
                        SceneCreator.displayMarker(t.getTeamColor());
                        break;
                }
              }
          }
          else{
              SceneCreator.hideMarker();
          }    
    }
    
    public boolean isBallOut(){
      VISIE.characters.Character c = SceneCharacterManager.getCharacterInPossession();
      
      if(c != null){
          return !Court.isInsideCourt(c.getPosition());
      }
      else{
          return !Court.isInsideCourt(ball.getBallPosition());
      }
    }
    
    private void doOutOfBoundsActivity(){
        
         GameManager.setOutState();
         
         if(SceneCharacterManager.getCharacterInPossession() != null){
             SceneCharacterManager.getCharacterInPossession().removePossession();
         }
         
         ball.setBallPosition(Court.getRestartLocation().clone().add(0, 0.5f, 0));
         ball.stopBall();
  }
    
    public Vector3f getBallPos(){
      return ball.getBallPosition();
  }
    
    private void doResetActivity(){
      
      GameManager.setInState();
      GameManager.setAttackingTeam(SceneCharacterManager.getCharacterInPossession().getTeamID());
      
      if(SceneCharacterManager.getCharacterInPossession() instanceof VISIE.characters.BasketballAgent){
          BasketballAgent ba =  (BasketballAgent)SceneCharacterManager.getCharacterInPossession();
          ba.planner.resetPossessionTime();
      }   
  }
    
  public void displayInstructions(Node guiNode){
      
      int state = GameManager.getGameState();
      int attackingTeam = GameManager.getAttackingTeam();
      guiNode.detachChildNamed("instructions");
      guiNode.detachChildNamed("JInstructions");
      SceneCreator.removeBallMarker();
      SceneCreator.removeDirectionalArrow();
      SceneCreator.removeDribbleArrow();
      
      if(state == 0 && player instanceof VISIE.characters.KinectPlayer){
          KinectPlayer kp = (KinectPlayer)player;
          if(kp.isTravelling()){
//                String s = "Please dribble the ball!\n";
//                String jText = "ドリブルお願いします！\n";
//                this.setGUIText(s, guiNode);
//                this.setJapaneseText(jText, guiNode);
                SceneCreator.setDribbleArrow(player.getFacingDirection(), ball.getBallPosition());
          }
      }
      else if(state == 1){
          String s = "Ball is out!\n";
          String jText = "ボールはアウト\n";
          
          if(player.getTeamID() != attackingTeam){
              s = s + "Retrieve the ball from the restart location!";
          }
          else{
              s = s + "Opponent will restart play!\n";
          }
          this.setGUIText(s, guiNode);   
          
          if(player.getTeamID() != attackingTeam){
              jText = jText + "スタートの位置にはボールを取って";
          }
          else{
              jText = jText + "相手はプレイを再スタートします";
          }
          this.setJapaneseText(jText, guiNode);
          
          SceneCreator.setBallMarker(ball.getBallPosition());
      }
      else if(state == 2){
          
          String s;
          String jText;
          
          if(attackingTeam == player.getTeamID()){
                s = "Opponent is restarting play!\n";
                jText = "相手はプレイを再スタートします\n";
          }
          else{
              if(player.equals(SceneCharacterManager.getCharacterInPossession())){
                s = "Take ball back to restart location!\n";
                jText = "ボールをスタート位置に持って行って";
                SceneCreator.setDirectionalArrow(player.getPosition());
              }
              else if(SceneCharacterManager.getCharacterInPossession() == null){
                 s = "Retrieve the ball!\n";
                 jText = "ボールを取って\n";
                 SceneCreator.setBallMarker(ball.getBallPosition());
              }
              else{
                s = "Teammate is taking ball to restart location!\n";
                jText = "仲間はスタート位置にボールを持って行っています\n";
              }
          }

          this.setGUIText(s, guiNode);
          this.setJapaneseText(jText, guiNode);
      }
      else if(state == 3){
          
          String s;
          String jText;
          
          if(attackingTeam == player.getTeamID()){         
              s = "You scored!\n";
              s = s + "Opponent will restart play!";
              jText = "あなたのチームの得点！\n";
              jText = jText + "相手は再スタートします";
          }
          else{
              s = "Opponent scored!\n";
              s = s + "Retrieve the ball!";
              jText = "相手チームの得点！\n";
              jText = jText + "ボールを取って";
          }
          this.setGUIText(s, guiNode);
          this.setJapaneseText(jText, guiNode);
          
          SceneCreator.setBallMarker(ball.getBallPosition());
      }   
  }
  
    private void setGUIText(String text, Node guiNode){
      BitmapText instructionText = new BitmapText(guiFont, false);
      instructionText.setSize(guiFont.getCharSet().getRenderedSize());
      instructionText.setText(text);
      instructionText.setLocalTranslation(resolution[0] * mainScreen + resolution[0]/2 - instructionText.getLineWidth()/2, resolution[1] * 0.9f, 0);
      instructionText.setColor(ColorRGBA.Red);
      instructionText.setName("instructions");
      instructionText.setBox(new Rectangle(0, 0, instructionText.getLineWidth(), instructionText.getLineHeight()));
      instructionText.setAlignment(BitmapFont.Align.Center);
      guiNode.attachChild(instructionText);
  }
    
    private void setJapaneseText(String text, Node guiNode){

      BitmapText instructionText = new BitmapText(JFont, false);
      instructionText.setSize(JFont.getCharSet().getRenderedSize());
      instructionText.setText(text);
      instructionText.setLocalTranslation(resolution[0] * mainScreen + resolution[0]/2 - instructionText.getLineWidth()/2, resolution[1] * 0.8f, 0);
      instructionText.setColor(ColorRGBA.Red);
      instructionText.setName("JInstructions");
      instructionText.setBox(new Rectangle(0, 0, instructionText.getLineWidth(), instructionText.getLineHeight()));
      instructionText.setAlignment(BitmapFont.Align.Center);
      guiNode.attachChild(instructionText);
    } 
    
    public void setScoreText(Node guiNode){
      guiNode.detachChildNamed("score");
      BitmapText scoreText = new BitmapText(guiFont, false);
      scoreText.setSize(guiFont.getCharSet().getRenderedSize() * 2);
      scoreText.setText(score[0] + "-" + score[1]);
      scoreText.setLocalTranslation((resolution[0] * (mainScreen + 1))  - scoreText.getLineWidth() - 5, resolution[1], 0);
      scoreText.setColor(ColorRGBA.Red);
      scoreText.setName("score");
      guiNode.attachChild(scoreText);
  }
 
    public void setTimeText(String timeString, Node guiNode){
       
      guiNode.detachChildNamed("time");
      BitmapText timeText = new BitmapText(guiFont, false);
      timeText.setSize(guiFont.getCharSet().getRenderedSize() * 2);
      timeText.setText(timeString);
      timeText.setLocalTranslation((resolution[0] * (mainScreen)) , resolution[1], 0);
      timeText.setColor(ColorRGBA.Red);
      timeText.setName("time");
      guiNode.attachChild(timeText);
    }
    
    public static int[] getScore(){
        return score;
    }
    
    public void setTwoTouch(boolean b){
        twoTouch = b;
    }
        
}
